package com.itwmk.service.impl.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itwmk.entity.Dish;
import com.itwmk.entity.DishDto;
import com.itwmk.entity.DishFlavor;
import com.itwmk.mapper.DishMapper;
import com.itwmk.service.impl.DishFavorService;
import com.itwmk.service.impl.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author wmk
 */
@Slf4j
@Transactional//开启事务控制，保证两张表数据一致性
@Service
public class DishImpl extends ServiceImpl<DishMapper, Dish> implements DishService {
    @Autowired
    private DishFavorService dishFavorService;
    @Override
    public void myAddDish(DishDto dto) {
        //保存菜品基本数据
        save(dto);
        //保存菜品口味
        List<DishFlavor> flavors = dto.getFlavors();
        for (DishFlavor d:flavors) {
            d.setDishId(dto.getId());
        }
        dishFavorService.saveBatch(flavors);
    }

    @Override
    public DishDto getByIdWithFlavor(Long id) {
        DishDto dto = new DishDto();
        LambdaQueryWrapper<DishFlavor> flavorWrapper = new LambdaQueryWrapper<>();

        Dish dish = getById(id);
        BeanUtils.copyProperties(dish,dto);
        flavorWrapper.eq(DishFlavor::getDishId,id);

        List<DishFlavor> dishFlavors = dishFavorService.list(flavorWrapper);
        dto.setFlavors(dishFlavors);

        return dto;

    }

    @Override
    public void updateWithFlavor(DishDto dto) {
        updateById(dto);

        LambdaQueryWrapper<DishFlavor> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DishFlavor::getDishId,dto.getId());
        dishFavorService.remove(wrapper);
        List<DishFlavor> flavors = dto.getFlavors();
        for (DishFlavor d:flavors) {
            d.setDishId(dto.getId());
        }
        dishFavorService.saveBatch(flavors);

    }
}
